package org.nowcoder.leetcode.BTree;

/**
 * Title  : 701. Insert into a Binary Search Tree
 * Source : https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/
 * Author : XrazYang
 * Date   : 2024-04-22
 */

public class LeetCode_701 {

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        } else {
            if (root.val < val) {
                root.right = insertIntoBST(root.right, val);
            }
            if (root.val > val) {
                root.left = insertIntoBST(root.left, val);
            }
        }
        return root;
    }

    public TreeNode insertIntoBST2(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        TreeNode current = root;
        while (true) {
            if (current.val < val) {
                if (current.right == null) {
                    current.right = new TreeNode(val);
                    break;
                }
                current = current.right;
            }

            if (current.val > val) {
                if (current.left == null) {
                    current.left = new TreeNode(val);
                    break;
                }
                current = current.left;
            }
        }
        return root;
    }
}
